<template>
  <CloudDialog
    :visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-close="handleClose">
    <a-form ref="formRef" layout="vertical" :model="formState" :rules="rules">
      <a-form-item
        label="文件后缀"
        field="suffix"
        asterisk-position="end"
        hide-asterisk>
        <a-textarea
          v-model="formState.suffix"
          placeholder="请输入文件后缀，内容可多个值，区分大小写，用英文逗号隔开"
          :max-length="200"
          :auto-size="{
            minRows: 5,
            maxRows: 5
          }"
          show-word-limit />
      </a-form-item>
      <a-form-item
        field="ttl"
        label="缓存时间"
        asterisk-position="end"
        hide-asterisk
        :rules="{ required: true, message: '请输入缓存时间' }"
        required>
        <section class="w-full flex items-center append-select">
          <a-input-number
            :model-value="Number(formState.ttl!)"
            :min="1"
            :max="formState.ttl_unit === 'd' ? 365 : 99999"
            :controls="false"
            :step="1"
            :precision="0"
            placeholder="请输入"
            class="flex-1"
            @update:model-value="(val) => (formState.ttl = val)">
          </a-input-number>
          <a-select
            v-model="formState.ttl_unit"
            class="!w-78px h-32px"
            :options="cacheTimeOptions"
            style="
              border-top: 1px solid var(---color-border-4, #dfe2e5);
              border-right: 1px solid var(---color-border-4, #dfe2e5);
              border-bottom: 1px solid var(---color-border-4, #dfe2e5);
              background: var(---color-fill-1, #f7f8fa);
            ">
          </a-select>
        </section>
      </a-form-item>
    </a-form>
  </CloudDialog>
</template>
<script lang="ts" setup>
import {
  getApiPresetCacheRule,
  updateApiPresetCacheRule
} from '@/apis/modules/resolve/rule'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
// import type { FormInstance } from '@arco-design/web-vue'
// const visible = defineModel({ default: false })

const { data } = useListRequest(getApiPresetCacheRule, {
  immediate: true
})
interface IProps {
  record?: any
  visible: boolean
  isAdd?: boolean
  index: number
}
//const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = reactive({
  suffix: '',
  ttl: 1,
  ttl_unit: 'd'
})

const rules = computed<Record<string, FieldRule[]>>(() => {
  const res: Record<string, FieldRule[]> = {
    suffix: [
      { required: true, message: '请输入文件后缀' },
      {
        validator: validateSuffix
      }
    ]
  }
  return res
})
const props = withDefaults(defineProps<IProps>(), {})

const emit = defineEmits(['reload', 'update:visible'])

const title = computed(() => (props.index === -1 ? '添加规则' : '编辑规则'))
const handleSubmit = async () => {
  const error = await formRef.value?.validate()
  if (error) return false

  if (props.index === -1) {
    data.value.push({
      suffix: formState.suffix.split(','),
      cache_time: formState.ttl + formState.ttl_unit
    })
  } else {
    data.value[props.index].suffix = formState.suffix.split(',')
    data.value[props.index].cache_time = formState.ttl + formState.ttl_unit
  }
  return updateApiPresetCacheRule({ list: data.value })
    .then(() => {
      ToastUtils.success('操作成功')

      emit('reload')
    })
    .catch((error) => {
      console.error(error)
    })
}

const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

// watch(
//   () => visible.value,
//   async (v) => {
//     await nextTick()
//     if (v) {
//       if (props.index !== -1) {
//         formState.suffix = props.record.suffix.join(',')
//         formState.ttl = props.record.cache_time.slice(0, -1)
//         formState.ttl_unit = props.record.cache_time.slice(-1)
//       }
//     } else {
//       formRef.value?.resetFields()
//     }
//   }
// )
onMounted(() => {
  if (props.index !== -1) {
    formState.suffix = props.record.suffix.join(',')
    formState.ttl = props.record.cache_time.slice(0, -1)
    formState.ttl_unit = props.record.cache_time.slice(-1)
  }
})
</script>
